<template>
  <mars-dialog customClass="dialog-nopadding" title="飞行漫游" width="330" top="60" :right="10" bottom="80" icon="take-off">
    <roam-route :flyData="flyData" @editData="editData" @roamStart="roamStart" />
  </mars-dialog>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from "vue"
import useLifecycle from "@mars/common/uses/use-lifecycle"
import RoamRoute from "./roam-route.vue"
import * as mapWork from "./map"
import { useWidget } from "@mars/common/store/widget"
import { logWarn } from "@mars/utils/mars-util"

const { activate, updateWidget, disable, isActivate } = useWidget()

// 启用map.ts生命周期
useLifecycle(mapWork)

// 取消工具栏高亮
onUnmounted(() => {
  disable("graphic-options")
  updateWidget("toolbar", "roamLine-list")
})


const flyData = ref<any[]>([])

mapWork.eventTarget.on("plot_graphicEditor", (event) => {
  handleWidgetGraphic(event)
})
// 数据更新
mapWork.eventTarget.on("refreshFlyData", async (event: any) => {
  switch (event.key) {
    case "new": {
      const dataArr = []
      event.data?.forEach((item) => {
        dataArr.push({ name: item.name ?? item.attr?.name ?? "未命名", key: item.id, id: item.id })
      })
      flyData.value = dataArr
      break
    }
    case "add": {
      if (flyData.value.length) {
        flyData.value.push(event.data)
      } else {
        flyData.value = [{ ...event.data }]
      }
      break
    }

    case "remove": {
      const index = flyData.value.findIndex((item) => item.id === event.id)
      if (index !== -1) {
        flyData.value.splice(index, 1)
      }

      handleWidgetGraphic({ disable: true })
      break
    }

    default:
      break
  }
})

function handleWidgetGraphic(event) {
  if (event.disable) {
    disable("graphic-options")
  } else {
    const data = { layerId: event.layerId, graphicId: event.graphicId }
    if (!isActivate("graphic-options")) {
      const isOpen = event.isOpen ?? true
      isOpen && activate({ name: "graphic-options", data })
    } else {
      updateWidget("graphic-options", data)
    }
  }
}


// 点击编辑
function editData(id: string) {
  if (!mapWork.graphicLayer.id || !id) {
    return
  }

  handleWidgetGraphic({ layerId: mapWork.graphicLayer.id, graphicId: id })
}

// 漫游路线面板开始漫游
async function roamStart(id: string | number) {
  const graphicOptions = mapWork.handleRoamById(id, "getOptions")
  if (graphicOptions) {
    activate({
      name: "roamLine",
      data: { graphicOptions }
    })
  } else {
    logWarn("漫游路线数据不存在")
  }
}
</script>

<style lang="less">
.dialog-nopadding {
  .mars-dialog__content {
    padding: 0 !important;
  }
}
</style>
